package com.mrx.xfriendship.event.listener;

import com.mrx.commons.util.DelayTask;
import com.mrx.xfriendship.event.event.ErrorEvent;
import com.mrx.xfriendship.model.dto.MailDTO;
import com.mrx.xfriendship.service.IMailService;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author : 肖康宁
 * @since : 2022-12-09 14:38
 **/
@Component
public class XEventListener {

    private static final Logger logger = LoggerFactory.getLogger(XEventListener.class);

    private static final String ADMIN_EMAIL = "1725338233@qq.com";

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @DubboReference
    private IMailService mailService;

    @Resource
    private DelayTask delayTask;

    @Async
    @EventListener({ErrorEvent.class})
    public void errorEventListener(ErrorEvent event) {
        logger.debug("errorEvent: {}", event.getSource().getMessage());
        delayTask.offerTask(() -> sendErrorMail(event.getSource()));
    }

    public void sendErrorMail(Throwable t) {
        MailDTO mailDTO = MailDTO.builder()
                .subject("【华夏交友圈】 " + formatter.format(LocalDateTime.now()) + " 异常告警")
                .text(StringUtils.toString(t)).sendTo(ADMIN_EMAIL)
                .build();
        logger.debug("准备发送异常告警邮件: {}", mailDTO);
        mailService.sendSimpleMail(mailDTO);
    }

}
